//
//  QLMDetailAddressVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/20.
//  Copyright © 2017年 hwd. All rights reserved.
//
#import "QLMDetailAddressVC.h"
#import "QLMDiscussVC.h"
#import <WebKit/WebKit.h>

#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>

@interface QLMDetailAddressVC ()<WKNavigationDelegate,WKUIDelegate>{
    UIButton *discussButton;
    WKWebView *awebview;
}

@property (nonatomic, strong) UIBarButtonItem *backItem;
@property (nonatomic, strong) UIBarButtonItem *closeItem;
@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation QLMDetailAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    // Do any additional setup after loading the view.

    CGRect webFrame=CGRectMake(0, 0, kScreen_width, kScreen_height-QLM_StatusBarAndNavigationBarHeight-IOS11_OR_LATER_SPACE(34));
    awebview=[[WKWebView alloc]  initWithFrame:webFrame];
    awebview.navigationDelegate=self;
    awebview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:awebview];
    
    [self addLeftButton];
    [self aCreatMainUI];
}

- (void)setupRightNavigationBar{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton setImage:[UIImage imageNamed:@"04_new"] forState:UIControlStateNormal];
    [rightButton setBackgroundColor:[UIColor clearColor]];
    rightButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    [rightButton addTarget:self action:@selector(showBottomNormalView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                   target:nil
                                   action:nil];
    fixedSpace.width = 0;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:rightItem,fixedSpace,nil];
}

//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//
//    if ([keyPath isEqualToString:@"estimatedProgress"]) {
//        self.progressView.progress = awebview.estimatedProgress;
//        if (self.progressView.progress == 1) {
//
//            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
//                self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
//            } completion:^(BOOL finished) {
//                self.progressView.hidden = YES;
//
//            }];
//        }
//    }else{
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
//}

//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
//    NSLog(@"开始加载网页 %@",webView.URL.absoluteString);
    if ([webView.URL.absoluteString containsString:@"tel:"]||[webView.URL.absoluteString containsString:@"sms:"]) {
        UIWebView *tmpwebView =[[UIWebView alloc] initWithFrame:CGRectZero];
        [tmpwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:webView.URL.absoluteString]]];
        [self.view addSubview:tmpwebView];
    }else{
        self.progressView.hidden = NO;
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        [self.view bringSubviewToFront:self.progressView];
    }
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    //加载完成后隐藏progressView
    self.progressView.hidden = YES;
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    [self _loadRequestWebview:_htmlurlStr];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    discussButton.hidden=YES;
}

- (void)dealloc {
//    [awebview removeObserver:self forKeyPath:@"estimatedProgress"];
//    awebview.navigationDelegate = nil;
//    [awebview stopLoading];
//    [awebview removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
//    [awebview removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))];
}

- (void)_loadRequestWebview:(NSString *)url{
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [awebview loadRequest:request];
}

- (void)aCreatMainUI{
    
    discussButton = [UIButton buttonWithType:UIButtonTypeCustom];
    discussButton.frame = CGRectMake(0, kScreen_height-44-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight, kScreen_width, 44);
    [discussButton setTitle:@"去咨询" forState:UIControlStateNormal];
    [discussButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    discussButton.backgroundColor = kButtonColor;
    discussButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    [discussButton addTarget:self action:@selector(discussButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    discussButton.hidden=YES;
    [self.view addSubview:discussButton];
}

#pragma mark - share
- (void)showBottomNormalView{
    [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
    
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageItemStyleType = UMSocialPlatformItemViewBackgroudType_IconAndBGRoundAndSuperRadius;
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        [self shareImageURLToPlatformType:platformType];
    }];
}

//分享网络图片
- (void)shareImageURLToPlatformType:(UMSocialPlatformType)platformType{
    
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"小马快修" descr:@"中国领先的工程机械共享赋能服务平台" thumImage:[UIImage imageNamed:@"shareIcon"]];
    shareObject.webpageUrl=_htmlurlStr;
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"Share fail with error %@",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                NSLog(@"response message is %@",resp.message);
                NSLog(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                NSLog(@"response data is %@",data);
            }
        }
        [self alertWithError:error];
    }];
}

- (void)alertWithError:(NSError *)error{
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"分享成功"];
    }else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"分享失败错误信息: %d\n%@",(int)error.code, str];
        }else{
            result = [NSString stringWithFormat:@"分享失败"];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享"
                                                    message:result
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - WKwebview delegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    //获取请求的url路径.
    NSString *url = navigationResponse.response.URL.absoluteString;
    _htmlurlStr=url;

    if([url containsString:@"machineDetails"]||[url containsString:@"accessoriesDetails"]){
        [self setupRightNavigationBar];
        discussButton.hidden=NO;
        CGRect webFrame=CGRectMake(0, 0, kScreen_width, kScreen_height-44-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight);
        [awebview setFrame:webFrame];
    }else if ([url containsString:@"m.duiba.com.cn"]){
    }else{
        [self setupRightNavigationBar];
        discussButton.hidden=YES;
        CGRect webFrame=CGRectMake(0, 0, kScreen_width, kScreen_height-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight);
        [awebview setFrame:webFrame];
    }
    decisionHandler(WKNavigationResponsePolicyAllow);
}

#pragma mark -
- (void)discussButtonAction:(UIButton *)btn{
    
    if (![[UserManager sharedManager] isUserLogin]) {//判断是否登录
        [self presentaLoginVC];
    }else{
        QLMDiscussVC *discussVC=[QLMDiscussVC new];
        discussVC.htmlurlStr=_htmlurlStr;
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:discussVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Action
- (void)presentaLoginVC{
    __weak __typeof(self)weakSelf = self;
    QLMLoginViewController *loginController = [QLMLoginViewController new];
    loginController.resultBlock=^(BOOL success){
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    };
    QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - 添加关闭按钮
- (void)addLeftButton{
    self.navigationItem.leftBarButtonItem = self.backItem;
}

//点击返回的方法
- (void)backNative{
    //判断是否有上一层H5页面
    if ([awebview canGoBack]) {
        //如果有则返回
        [awebview goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    } else {
        [self closeNative];
    }
}

//关闭H5页面，直接回到原生页面
- (void)closeNative{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - init
- (UIBarButtonItem *)backItem{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *image = [UIImage imageNamed:@"back"];
        [btn setImage:image forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        //左对齐
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        btn.frame = CGRectMake(0, 0, 40, 40);
        _backItem.customView = btn;
    }
    return _backItem;
}

- (UIBarButtonItem *)closeItem{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
        _closeItem.tintColor = [UIColor whiteColor];
    }
    return _closeItem;
}

@end
